<?php

namespace common\components\wechat;

use Yii;
use yii\base\InvalidConfigException;
use common\components\wechat\components\BasePayment;
use yii\helpers\ArrayHelper;
use common\helpers\Utils;

/**
 * 微信支付
 * 注:部分功能因API的整体和功能性, 拆分为单独的类调用请查看compoents/mp文件夹
 * @package calmez\wechat\sdk
 */
class PaymentWechat extends BasePayment {

    /**
     * 公众账号ID
     * 微信分配的公众账号ID（企业号corpid即为此appId）
     * @var String(32)
     */
    public $appid;

    /**
     * 商户号
     * 微信支付分配的商户号
     * @var String(32)
     */
    public $mch_id;

    /**
     * 合作商户密钥
     * @var String(32)
     */
    public $partner_key;

    /**
     * @inheritdoc
     * @throws InvalidConfigException
     */
    public function init() {
        if ($this->appid === null) {
            throw new InvalidConfigException('The "appid" property must be set.');
        }
    }

    const UNIFIED_ORDER_URL = '/pay/unifiedorder';

    public function prepay($config) {
        if (!isset($config['class'])) {
            $config['class'] = 'common\components\wechat\mp\UnifiedOrder';
        }
        $this->setTransport($config);
        $attributes = array_filter($this->transport->getAttributes());
        $attributes['sign'] = parent::generateSignature($attributes, $this->partner_key);

        $post = $this->xml($attributes);
        $response = $this->httpRaw(self::UNIFIED_ORDER_URL, $post);
        Yii::error($response);
        $prepayData = $this->parseRequestXml($response);
        $prepayId = ArrayHelper::getValue($prepayData, 'prepay_id');
        if (!$prepayId) {
            Yii::error([
                'result' => $prepayData,
                'xml' => $post,
                'partner_key' => $this->partner_key,
                'attributes' => $attributes
            ], __METHOD__);
            return [];
        }

        $openid = ArrayHelper::getValue($attributes, 'openid');
        $data = [];
        if ($openid) {
            $data = [
                'appId' => $this->appid,
                'timeStamp' => strval(time()),
                'nonceStr' => Utils::random(32),
                'package' => 'prepay_id=' . $prepayId,
                'signType' => 'MD5',
            ];
            $data['paySign'] = static::generateSignature($data, $this->partner_key);
        } else {
            $data = [
                'appid' => $this->appid,
                'partnerid' => $this->mch_id,
                'prepayid' => $prepayId,
                'package' => 'Sign=WXPay',
                'noncestr' => Utils::random(32),
                'timestamp' => strval(time()),
            ];
            $data['sign'] = static::generateSignature($data, $this->partner_key);
        }
        
        Yii::error($data);

        return $data;
    }

    const REFUND_URL = '/secapi/pay/refund';
    const MMPAYMKTTRANSFERS_URL = '/mmpaymkttransfers/promotion/transfers';

    public function refund($config) {
        if (!isset($config['class'])) {
            $config['class'] = 'common\components\wechat\mp\Refund';
        }
        $this->setTransport($config);
        $attributes = array_filter($this->transport->getAttributes());
        $attributes['sign'] = parent::generateSignature($attributes, $this->partner_key);
        $post = $this->xml($attributes);
        $response = $this->curl_post_ssl(self::REFUND_URL, $post);
        return $this->parseRequestXml($response);
    }

    public function brokerage($config) {
        if (!isset($config['class'])) {
            $config['class'] = 'common\components\wechat\mp\Mmpaymkttransfers';
        }
        $config['mch_appid'] = $this->appid;
        $config['mchid'] = $this->mch_id;
        $this->setTransport($config);
        $attributes = array_filter($this->transport->getAttributes());
        $attributes['sign'] = parent::generateSignature($attributes, $this->partner_key);
        $post = $this->xml($attributes);
        $response = $this->curl_post_ssl(self::MMPAYMKTTRANSFERS_URL, $post);
        return $this->parseRequestXml($response);
    }

}
